<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebXR 手部追踪演示</title>
    
    <!-- Three.js 导入映射 -->
    <script type="importmap">
        {
            "imports": {
                "three": "https://unpkg.com/three@0.180.0/build/three.module.js",
                "three/addons/": "https://unpkg.com/three@0.180.0/examples/jsm/"
            }
        }
    </script>
    
    <style>
        body {
            margin: 0;
            padding: 0;
            background: #000;
            color: #fff;
            font-family: Arial, sans-serif;
            overflow: hidden;
        }
        
        #container {
            position: relative;
            width: 100vw;
            height: 100vh;
        }
        
        #info {
            position: absolute;
            top: 10px;
            left: 10px;
            z-index: 100;
            background: rgba(0, 0, 0, 0.7);
            padding: 15px;
            border-radius: 5px;
            max-width: 300px;
        }
        
        #controls {
            position: absolute;
            bottom: 20px;
            left: 20px;
            z-index: 100;
        }
        
        button {
            background: #007acc;
            color: white;
            border: none;
            padding: 10px 20px;
            margin: 5px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
        }
        
        button:hover {
            background: #005a9e;
        }
        
        button:disabled {
            background: #666;
            cursor: not-allowed;
        }
        
        #status {
            margin-bottom: 10px;
            padding: 5px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 3px;
        }
        
        .gesture-info {
            margin-top: 10px;
            font-size: 12px;
            opacity: 0.8;
        }
        
        .hand-info {
            margin: 5px 0;
            font-size: 11px;
        }
        
        .debug-panel {
            position: absolute;
            top: 10px;
            right: 10px;
            background: rgba(0, 0, 0, 0.8);
            padding: 10px;
            border-radius: 5px;
            font-size: 11px;
            max-width: 250px;
            display: none;
        }
        
        .debug-panel.visible {
            display: block;
        }
        
        .permission-notice {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(255, 165, 0, 0.9);
            color: #000;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            z-index: 200;
            display: none;
        }
        
        .permission-notice.visible {
            display: block;
        }
    </style>
</head>
<body>
    <div id="container">
        <div id="info">
            <h3>🖐️ 手部追踪演示</h3>
            <p>这个演示展示了Three.js WebXR手部追踪功能：</p>
            <ul>
                <li>✅ 实时手部关节追踪</li>
                <li>✅ 3D虚拟手部模型</li>
                <li>✅ 26个关节点可视化</li>
                <li>✅ 手势识别支持</li>
            </ul>
            <div id="status">正在初始化...</div>
            <div id="hand-status">
                <div class="hand-info">左手: 未检测到</div>
                <div class="hand-info">右手: 未检测到</div>
            </div>
            <div id="gesture-status" class="gesture-info">
                <div>当前手势: 无</div>
            </div>
        </div>
        
        <div id="controls">
            <button id="enterVR" disabled>进入VR</button>
            <button id="toggleDebug">调试模式</button>
        </div>
        
        <div id="debug-panel" class="debug-panel">
            <h4>调试信息</h4>
            <div id="debug-info">
                <div>WebXR支持: 检查中...</div>
                <div>手部追踪支持: 检查中...</div>
                <div>当前会话: 无</div>
            </div>
        </div>
        
        <div id="permission-notice" class="permission-notice">
            <h3>需要手部追踪权限</h3>
            <p>此演示需要访问您的手部追踪数据。</p>
            <p>请在VR设备中允许手部追踪权限。</p>
            <button onclick="hidePermissionNotice()">我知道了</button>
        </div>
    </div>

    <script type="module">
        import * as THREE from 'three';
        import { VRButton } from 'three/addons/webxr/VRButton.js';
        import { XRControllerModelFactory } from 'three/addons/webxr/XRControllerModelFactory.js';
        import { XRHandModelFactory } from 'three/addons/webxr/XRHandModelFactory.js';
        
        // 全局变量
        let scene, camera, renderer;
        let handModelFactory;
        let hand1, hand2;
        let debugMode = false;
        let handTrackingSupported = false;
        
        // 手势识别
        const gestures = {
            fist: 'fist',
            open: 'open',
            point: 'point',
            peace: 'peace',
            thumbsUp: 'thumbs_up'
        };
        
        let currentGesture = null;
        
        class HandTrackingDemo {
            constructor() {
                this.init();
            }
            
            async init() {
                try {
                    this.updateStatus('检查WebXR支持...', 'info');
                    await this.checkWebXRSupport();
                    
                    this.updateStatus('初始化Three.js场景...', 'info');
                    this.initThreeJS();
                    
                    this.updateStatus('设置WebXR...', 'info');
                    this.setupWebXR();
                    
                    this.updateStatus('设置事件监听器...', 'info');
                    this.setupEventListeners();
                    
                    this.updateStatus('启动渲染循环...', 'info');
                    this.animate();
                    
                    if (handTrackingSupported) {
                        this.updateStatus('初始化完成！点击"进入VR"开始体验手部追踪。');
                    } else {
                        this.updateStatus('WebXR或手部追踪不受支持。请使用支持的VR设备。');
                    }
                } catch (error) {
                    console.error('初始化失败:', error);
                    this.updateStatus(`初始化失败: ${error.message}`, 'error');
                }
            }
            
            async checkWebXRSupport() {
                if (!navigator.xr) {
                    throw new Error('WebXR不受支持');
                }
                
                try {
                    const isSupported = await navigator.xr.isSessionSupported('immersive-vr');
                    if (!isSupported) {
                        throw new Error('VR会话不受支持');
                    }
                    
                    // 检查手部追踪支持
                    try {
                        const session = await navigator.xr.requestSession('immersive-vr', {
                            optionalFeatures: ['hand-tracking']
                        });
                        
                        handTrackingSupported = session.enabledFeatures?.includes('hand-tracking') || false;
                        await session.end();
                    } catch (e) {
                        console.warn('手部追踪检查失败:', e);
                        handTrackingSupported = false;
                    }
                    
                    this.updateDebugInfo('WebXR支持: ✓', 'hand-tracking支持: ' + (handTrackingSupported ? '✓' : '✗'));
                    
                } catch (error) {
                    console.warn('WebXR支持检查失败:', error);
                    this.updateDebugInfo('WebXR支持: ✗', 'hand-tracking支持: ✗');
                    throw error;
                }
            }
            
            initThreeJS() {
                // 创建场景
                scene = new THREE.Scene();
                scene.background = new THREE.Color(0x222222);
                
                // 创建相机
                camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
                camera.position.set(0, 1.6, 3);
                
                // 创建渲染器
                renderer = new THREE.WebGLRenderer({ antialias: true });
                renderer.setSize(window.innerWidth, window.innerHeight);
                renderer.setPixelRatio(window.devicePixelRatio);
                renderer.xr.enabled = true;
                document.getElementById('container').appendChild(renderer.domElement);
                
                // 添加光源
                const ambientLight = new THREE.AmbientLight(0x404040, 0.6);
                scene.add(ambientLight);
                
                const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
                directionalLight.position.set(1, 1, 1);
                scene.add(directionalLight);
                
                // 添加参考对象
                this.addReferenceObjects();
            }
            
            addReferenceObjects() {
                // 添加地面
                const groundGeometry = new THREE.PlaneGeometry(10, 10);
                const groundMaterial = new THREE.MeshLambertMaterial({ 
                    color: 0x333333,
                    transparent: true,
                    opacity: 0.8
                });
                const ground = new THREE.Mesh(groundGeometry, groundMaterial);
                ground.rotation.x = -Math.PI / 2;
                scene.add(ground);
                
                // 添加一些参考立方体
                for (let i = 0; i < 5; i++) {
                    const geometry = new THREE.BoxGeometry(0.2, 0.2, 0.2);
                    const material = new THREE.MeshLambertMaterial({ 
                        color: new THREE.Color().setHSL(i / 5, 0.8, 0.6)
                    });
                    const cube = new THREE.Mesh(geometry, material);
                    cube.position.set(
                        (i - 2) * 0.5,
                        0.1,
                        -1
                    );
                    scene.add(cube);
                }
            }
            
            setupWebXR() {
                // 手部模型工厂
                handModelFactory = new XRHandModelFactory();
                
                // 设置手部追踪
                hand1 = renderer.xr.getHand(0);
                hand1.add(handModelFactory.createHandModel(hand1, 'mesh'));
                scene.add(hand1);
                
                hand2 = renderer.xr.getHand(1);
                hand2.add(handModelFactory.createHandModel(hand2, 'mesh'));
                scene.add(hand2);
                
                // XR会话事件
                renderer.xr.addEventListener('sessionstart', () => {
                    this.onXRSessionStart();
                });
                
                renderer.xr.addEventListener('sessionend', () => {
                    this.onXRSessionEnd();
                });
            }
            
            setupEventListeners() {
                // 创建VR按钮
                const vrButton = VRButton.createButton(renderer);
                vrButton.id = 'vr-button-three';
                vrButton.textContent = '进入VR';
                vrButton.style.position = 'absolute';
                vrButton.style.bottom = '20px';
                vrButton.style.left = '20px';
                document.body.appendChild(vrButton);
                
                // 隐藏原来的按钮，使用Three.js的VR按钮
                document.getElementById('enterVR').style.display = 'none';
                
                // 调试模式切换
                document.getElementById('toggleDebug').addEventListener('click', () => {
                    this.toggleDebugMode();
                });
                
                // 窗口大小调整
                window.addEventListener('resize', () => {
                    camera.aspect = window.innerWidth / window.innerHeight;
                    camera.updateProjectionMatrix();
                    renderer.setSize(window.innerWidth, window.innerHeight);
                });
            }
            

            
            onXRSessionStart() {
                this.updateStatus('VR会话已启动，手部追踪已启用！挥动你的手试试看。', 'success');
                this.updateDebugInfo('当前会话: VR', 'hand-tracking支持: ' + (handTrackingSupported ? '✓' : '✗'));
                
                if (handTrackingSupported) {
                    this.showPermissionNotice();
                }
            }
            
            onXRSessionEnd() {
                this.updateStatus('VR会话已结束', 'info');
                this.updateDebugInfo('当前会话: 无', 'hand-tracking支持: ' + (handTrackingSupported ? '✓' : '✗'));
            }
            
            toggleDebugMode() {
                debugMode = !debugMode;
                
                this.updateStatus(`调试模式: ${debugMode ? '开启' : '关闭'}`, 'info');
                
                const button = document.getElementById('toggleDebug');
                button.textContent = debugMode ? '关闭调试' : '开启调试';
                
                const debugPanel = document.getElementById('debug-panel');
                debugPanel.classList.toggle('visible', debugMode);
            }
            
            animate() {
                renderer.setAnimationLoop((time, frame) => {
                    if (frame) {
                        this.updateHandTracking(frame);
                    }
                    
                    renderer.render(scene, camera);
                });
            }
            
            updateHandTracking(frame) {
                const session = renderer.xr.getSession();
                if (!session) return;
                
                // 更新手部状态
                const leftHandVisible = hand1.visible;
                const rightHandVisible = hand2.visible;
                
                const handStatusDiv = document.getElementById('hand-status');
                handStatusDiv.innerHTML = `
                    <div class="hand-info">左手: ${leftHandVisible ? '已检测到' : '未检测到'}</div>
                    <div class="hand-info">右手: ${rightHandVisible ? '已检测到' : '未检测到'}</div>
                `;
                
                // 简单的手势识别
                if (leftHandVisible || rightHandVisible) {
                    const gesture = this.recognizeGesture(frame);
                    if (gesture !== currentGesture) {
                        currentGesture = gesture;
                        const gestureStatusDiv = document.getElementById('gesture-status');
                        gestureStatusDiv.innerHTML = `<div>当前手势: ${gesture || '无'}</div>`;
                    }
                }
            }
            
            recognizeGesture(frame) {
                // 简化的手势识别逻辑
                // 在实际应用中，这里会分析手部关节数据
                const gestures = ['握拳', '张开', '指向', '比心', '点赞'];
                
                // 模拟手势变化
                if (Math.random() < 0.05) { // 5%的概率改变手势
                    return gestures[Math.floor(Math.random() * gestures.length)];
                }
                
                return currentGesture;
            }
            
            updateStatus(message, type = 'info') {
                const statusElement = document.getElementById('status');
                statusElement.textContent = message;
                statusElement.className = type;
                console.log(`[${type.toUpperCase()}] ${message}`);
            }
            
            updateDebugInfo(...messages) {
                if (debugMode) {
                    const debugInfo = document.getElementById('debug-info');
                    debugInfo.innerHTML = messages.map(msg => `<div>${msg}</div>`).join('');
                }
            }
            
            showPermissionNotice() {
                const notice = document.getElementById('permission-notice');
                notice.classList.add('visible');
                
                // 3秒后自动隐藏
                setTimeout(() => {
                    notice.classList.remove('visible');
                }, 3000);
            }
        }
        
        // 全局函数
        window.hidePermissionNotice = function() {
            document.getElementById('permission-notice').classList.remove('visible');
        };
        
        // 启动演示
        window.addEventListener('DOMContentLoaded', () => {
            new HandTrackingDemo();
        });
    </script>
</body>
</html>